/*
 * To change this template, chooutpute Tools | Templates
 * and open the template in the editor.
 */
package idv.cloudee.proxy2.test;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 *
 * @author Cloudee
 */
class CopyOutputStream extends OutputStream {

    private final OutputStream output;
    private final OutputStream copy;
    private final boolean forDisplay;

    public CopyOutputStream(OutputStream output, OutputStream copy) {
        this.output = output;
        this.copy = copy;//new BufferedOutputStream(copy);
        forDisplay = false;
    }

    public CopyOutputStream(OutputStream output, OutputStream copy, boolean forDisplay) {
        this.output = output;
        this.copy = copy;
        this.forDisplay = forDisplay;
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        output.write(b, off, len);
        if (forDisplay) {
            if (off + len > b.length) {
                throw new IndexOutOfBoundsException();
            }
            for (int i = off, max = off + len; i < max; i++) {
                int bo = b[i] & 0xff;
                if (bo >= 26) {
                    copy.write(bo);
                }
            }
        } else {
            copy.write(b, off, len);
        }
        copy.flush();
    }

    @Override
    public void write(byte[] b) throws IOException {
        output.write(b);
        if (forDisplay) {
            for (int i = 0, max = b.length; i < max; i++) {
                int bo = b[i] & 0xff;
                if (bo >= 26) {
                    copy.write(bo);
                }
            }
        } else {
            copy.write(b);
        }
        copy.flush();
    }

    public void write(int b) throws IOException {
        output.write(b);
        if (forDisplay && b < 26) {
        } else {
            copy.write(b);
        }
        copy.flush();
    }

    @Override
    public void flush() throws IOException {
        output.flush();
        copy.flush();
    }

    @Override
    public void close() throws IOException {
        output.close();
        copy.flush();
    }
}
